const mqtt = require('aliyun-iot-mqtt');
//设备身份信息
var options = {
  productKey: "k1ku0DtYMnD",
  deviceName: "sb001",
  deviceSecret: "b897b8db0c10d371d6d32dd3cdfe6a4f",
  host: "iot-06z00dpx1o9dd9r.mqtt.iothub.aliyuncs.com"
};

//建立MQTT连接
const client = mqtt.getAliyunIotMqttClient(options);
//订阅云端指令Topic
client.subscribe(`/${options.productKey}/${options.deviceName}/user/get`)
client.subscribe(`/sys/${options.productKey}/${options.deviceName}/thing/event/property/post_reply`)
client.on('message', function (topic, message) {
  console.log("topic " + topic)
  console.log("message " + message)
})

setInterval(function () {
  //定时上报用电量数据
  client.publish(`/sys/${options.productKey}/${options.deviceName}/thing/event/property/post`, getPostData(), { qos: 0 });
}, 5 * 1000);

//电池电量百分比 取值范围：0 ~ 100
var batteryPercentage = 100;

function getPostData() {
	
	//血氧  取值范围：0 ~ 100
	var xueyang = Math.floor((Math.random() * 20) + 90);
	//体温  取值范围：35 ~ 43
	var bodyTemp = Math.floor((Math.random() * 10) + 35);
	//心率  取值范围：1 ~ 1000
	var heartRate = Math.floor((Math.random() * 20) + 70);
	
	var random = [0,1,2,3,4,5][Math.floor(Math.random() * 5)];
	
	if(random === 3 ){
		batteryPercentage--;
	}
	
  const payloadJson = {
    id: Date.now(),
    version: "1.0",
    params: {
	  BodyTemp: bodyTemp,
	  HeartRate: heartRate,
	  xueyang: xueyang,
	  BatteryPercentage: batteryPercentage
    },
    method: "thing.event.property.post"

  }
  console.log("payloadJson " + JSON.stringify(payloadJson))
  return JSON.stringify(payloadJson);
}